package com.hk.core.security.cas.userdetails;

import com.hk.commons.util.ConverterUtils;
import com.hk.core.authentication.security.SecurityUserPrincipal;
import org.apereo.cas.client.authentication.AttributePrincipal;
import org.apereo.cas.client.validation.Assertion;
import org.springframework.security.cas.userdetails.AbstractCasAssertionUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Map;

/**
 * 将cas服务端返回的认证通过后的用户信息，转换成 UserDetails
 */
public class GrantAuthenticationUserDetailsService extends AbstractCasAssertionUserDetailsService {

    @Override
    protected UserDetails loadUserDetails(Assertion assertion) {
        AttributePrincipal principal = assertion.getPrincipal();
        Map<String, Object> attributes = principal.getAttributes();
        return new SecurityUserPrincipal()
                .setUserId(ConverterUtils.defaultConvert(attributes.get("id"), Long.class))
                .setAccount(principal.getName())
                .setAreaCode(ConverterUtils.defaultConvert(attributes.get("areaCode"), Integer.class))
                .setMobileNumber(ConverterUtils.defaultConvert(attributes.get("mobileNumber"), String.class))
                .setGender(ConverterUtils.defaultConvert(attributes.get("gender"), Byte.class))
                .setIconPath(ConverterUtils.defaultConvert(attributes.get("iconPath"), String.class));//TODO: 其它属性
    }
}
